<?php
/**
 *
 * @author 孙春雷
 *        
 */
class Model_Inventories extends Modelnewerp {
	
	// 库存表字段的常量
	protected $id = 'id';
	const inventory_date = 'inventory_date';
	const sku = 'sku';
	const sku_name = 'sku_name';
	const sku_standard = 'sku_standard';
	const storage_position = 'storage_position';
	const quantity = 'quantity';
	const cost = 'cost';

	/**
	 * 调用的数据表
	 *
	 * @var unknown
	 */
	protected $_table = 'inventories';

	/**
	 * 根据时间获取所有sku的数量和成本
	 *
	 * @param unknown $date        	
	 */
	public function getCountAndCost($date, $sku = NULL)
	{
		// 定义结果数组
		$result = array ();
		
		// 统计某月的数量和成本
		$sql = DB::select( array (
				self::sku,
				'sku' 
		), array (
				self::quantity,
				'count' 
		), array (
				self::cost,
				'cost' 
		) )->from( $this->_table )
			->where( self::inventory_date, '=', $date );
		if ($sku)
		{
			$sql->where( self::sku, '=', $sku );
		}
		$opening = $sql->execute( $this->_db )
			->as_array();
		// 格式化数组
		foreach ( $opening as $c )
		{
			$sku_value = strtoupper( $c ['sku'] );
			$result [$sku_value] ['count'] = $c ['count'];
			$result [$sku_value] ['cost'] = round($c ['cost'],2);
		}
		
		return $result;
	}

	/**
	 * 查询是否已经统计过期末库存
	 *
	 * @param unknown $sku        	
	 * @param unknown $date        	
	 */
	public function get_id($sku, $date)
	{
		$result = DB::select( $this->id )->from( $this->_table )
			->where( self::sku, '=', $sku )
			->where( self::inventory_date, '=', $date );
		$result = $result->execute( $this->_db )
			->current();
		if ($result)
			return $result [$this->id];
		return 0;
	}
}
